﻿using UnityEngine;

using KaoticSSB.Online;

namespace KaoticSSB.Menus
{
	public class ServerListScreen : MonoBehaviour 
	{
		public float UpdateTimeIncrement = 1.0f;

		public void Start()
		{
			mCurrentUpdateTimer = 0.0f;
			mServers = null;
			MasterServer.ClearHostList();
			MasterServer.RequestHostList("KaoticSSB");
		}
		
		public void Update()
		{
			mCurrentUpdateTimer -= Time.deltaTime;
			if(mCurrentUpdateTimer <= 0.0f)
			{
				mCurrentUpdateTimer = UpdateTimeIncrement;
				GetServers();
			}
		}
		
		public void OnGUI()
		{
			GUILayout.BeginHorizontal();
			GUILayout.Space(5);
			GUILayout.BeginVertical();
			GUILayout.Space(5);

			//back button
			GUILayoutOption[] backOptions = { GUILayout.Width(65), GUILayout.Height (35) };
			if(GUILayout.Button("Back", backOptions))
		   	{
				Application.LoadLevel ("TitleScene");
			}

		    //create server
		    GUILayoutOption[] options = { GUILayout.Width(100), GUILayout.Height (35) };
			if(GUILayout.Button ("Create Server", options))
			{
				if(NetworkManager.StartServer())
				{
					LoadGame ();
				}
			}	
			GUILayout.Space(5);

			//display servers
			if(mServers != null)
			{
				// Go through all the hosts in the host list
				foreach (HostData element in mServers)
				{
					GUILayout.BeginHorizontal();	
					string name = element.gameName + " " + element.connectedPlayers + " / " + element.playerLimit;
					GUILayout.Label(name);	
					GUILayout.Space(5);
					string hostInfo;
					hostInfo = "[";
					foreach (string host in element.ip)
					{
						hostInfo = hostInfo + host + ":" + element.port + " ";
					}
					hostInfo = hostInfo + "]";
					GUILayout.Label(hostInfo);	
					GUILayout.Space(5);
					GUILayout.Label(element.comment);
					GUILayout.Space(5);
					GUILayout.FlexibleSpace();
					if (GUILayout.Button("Connect"))
					{
						// Connect to HostData struct, internally the correct method is used (GUID when using NAT).
						NetworkConnectionError error = Network.Connect(element);	
						if(error == NetworkConnectionError.NoError)
						{
							LoadGame();
						}
					}
					GUILayout.EndHorizontal();	
				}
			}
			GUILayout.EndVertical();
			GUILayout.EndHorizontal();	
		}

		private void GetServers()
		{
			mServers = MasterServer.PollHostList();
			MasterServer.ClearHostList();
			MasterServer.RequestHostList("KaoticSSB");
		}

		private void LoadGame()
		{
			NetworkManager.Connected = true;
			Application.LoadLevel ("BattleStage");
		}

		private float mCurrentUpdateTimer;
		private HostData[] mServers;
	}
}